<template>
  <div class="app-container">
    <div id="app">
      <div class="super-box">
        <div class="xchat-left">
          <div class="xtop">
            <img
              class="xlogo"
              src="../../../assets/images/login-background.jpg"
            />
            <p class="xsname"><b>用户列表</b></p>
          </div>
          <div
            v-for="user in userList"
            :key="user.senderId"
            class="chat-user"
            :class="{ selected: user.campUser.userId === toUser }"
            @click="selectUser(user)"
          >
            <img class="userimg" :src="imgurl + user.campUser.imageUrl" />

            <p class="userxsname">
              <b :uuid="user.uuid">{{ user.campUser.username }}</b>
            </p>
          </div>
        </div>
        <div class="xchat">
          <div class="xtop">
            <p class="xsname">客服端</p>
          </div>
          <div class="xmid">
            <div
              v-for="(msg, index) in chatList1"
              :key="index"
              :class="msg.senderClass"
            >
              <div class="xmsg" v-if="msg.senderId == toUser">
                <img
                  class="userimgliaot"
                  :src="imgurl + msg.campUser.imageUrl"
                />
                <div class="shuang">
                  <div class="xfrom1">
                    {{ msg.campUser.username }} - {{ msg.createTime }}
                  </div>
                  <!-- <p class="xmessage1" v-html="msg.content"> -->
                  <div class="xmessage_box"></div>
                  <p class="xmessage1">
                    {{ msg.content }}
                  </p>
                </div>
              </div>

              <div class="kxmg" v-if="msg.senderId != toUser">
                <img
                  class="userimgliaot_kefu"
                  :src="imgurl + msg.campUser.imageUrl"
                />
                <div class="shuang_kefu">
                  <div class="xfrom1">
                    {{ msg.createTime }} - {{ msg.campUser.username }}
                  </div>
                  <!-- <p class="xmessage1" v-html="msg.content"> -->
                  <div class="xmessage_box_kefu"></div>
                  <p class="xmessage1_kefu">
                    {{ msg.content }}
                  </p>
                </div>
              </div>
            </div>
          </div>

          <div class="xbottom">
            <textarea
              class="xsendmsg"
              v-model="messageContent"
              placeholder="请输入"
            ></textarea>
            <div class="xgsend">
              <button class="xsend" @click="send">发送</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  userSenderList,
  listService,
  getService,
  addService,
  updateService,
  delService,
  getBySenderIdAndByReceiverId,
} from "@/api/camp/service";
import Cookies from "js-cookie";
import { getToken } from "@/utils/auth";
export default {
  name: "Service",
  data() {
    return {
      kefuinfo: { kefuname: "客服", kefuimg: "", kefumessage: "asd" },
      userinfo1: {},
      chatList1: [],
      socket: null,
      messages: [],
      id1: "",
      imgurl: "http://localhost:8080",
      BASE_URL: "ws://127.0.0.1:8080/chat",
      websocket: null,
      uuid: "888888888888888888888", // 客服 UUID
      fromName: "客服", // 客服名称
      toUser: "", // 当前选中的用户 UUID
      userInfo: { uuid: null, nickname: null, ip: null },
      userList: [], // 用户列表
      messages: [], // 消息列表
      messageContent: "", // 待发送的消息内容
      quer: {},
      queryParams: {
        messageId: null,
        senderId: null,
        receiverId: null,
        content: null,
      },
    };
  },
  created() {
    this.getList();
  },
  //查询聊天记录表

  methods: {
    getList() {
      this.loading = true;
      userSenderList().then((response) => {
        console.log("22222222222:", response);
        this.userList = response.rows;
        console.log("userlist:", this.userList);
        if (response.rows != null || response.rows != undefined) {
          this.toUser = response.rows[0].campUser.userId;
        }

        console.log("this.toUser:", this.toUser);
      });
    },
    sendMessage() {
      var message = this.toUser + ":" + this.messageContent;
      // this.socket.send(JSON.stringify(message));
      this.socket.send(message);

      const time = "";
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      _this.time = yy + "/" + mm + "/" + dd + " " + hh + ":" + mf + ":" + ss;

      // this.chatList1.push({
      //   campUser: {
      //     userId: "1",
      //     imageUrl:
      //       "/profile/upload/2024/12/26/01254b583ff2e6a801219c77b9a15a_20241226085411A001.jpg",
      //     username: "客服",
      //   },
      //   content: this.messageContent,
      //   createTime: _this.time,

      // });
      getBySenderIdAndByReceiverId(this.id1).then((response) => {
        console.log("12312312312312312:", response);
        this.chatList1 = response.rows;
      });
      this.messageContent = "";
    },

    selectUser(user) {
      this.chatList1 = [];
      this.userinfo1 = {};
      this.toUser = "";
      this.userinfo1 = user;
      this.toUser = user.campUser.userId;
      this.id1 = user.campUser.userId;

      // 加载与该用户的历史消息
      getBySenderIdAndByReceiverId(this.id1).then((response) => {
        console.log("12312312312312312:", response);
        this.chatList1 = response.rows;
      });
    },
    send() {
      this.sendMessage();
    },
    dateTime2str(dateTime, format) {
      let z = {
        y: dateTime.getFullYear(),
        M: dateTime.getMonth() + 1,
        d: dateTime.getDate(),
        h: dateTime.getHours(),
        m: dateTime.getMinutes(),
        s: dateTime.getSeconds(),
      };
      return format.replace(/(y+|M+|d+|h+|m+|s+)/g, (v) => {
        return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2);
      });
    },
  },
  mounted() {
    const TokenKey = "Admin-Token";
    var token = Cookies.get(TokenKey);
    console.log("token: ", Cookies.get(TokenKey));
    var url = "ws://localhost:8080/chat" + "?token=" + token;
    this.socket = new WebSocket(url);
    this.socket.addEventListener("open", () => {
      console.log("WebSocket连接已打开");
    });
    var that = this;
    // 接受的消息
    this.socket.addEventListener("message", (event) => {
      const url = that.userinfo1.campUser.imageUrl;
      const name = that.userinfo1.campUser.username;
      const time = that.userinfo1.campUser.createTime;
      console.log(event.data.split(":"), "会话数据");
      // console.log(event.data,"会话数据")
      if (event.data.split(":")[0] == that.toUser) {
        that.chatList1.push({
          campUser: {
            userId: event.data?.split(":")[0],
            imageUrl: url,
            username: name,
          },
          content: event.data?.split(":")[2],
          createTime: time,
          // id: event.data?.split(":")[0],
          // chatData: event.data?.split(":")[2],
          // url: url,
          // name: name,
        });
      }
      //查询历史消息
      getBySenderIdAndByReceiverId(this.id1).then((response) => {
        console.log("12312312312312312:", response);
        // this.messages = response.data;
        // chatList1
        this.chatList1 = response.rows;
        // console.log("messagelist1111111111111:", this.chatList1);
      });
      that.toUser = event.data?.split(":")[0];
      console.log("usertype111111111", that.toUser);
      console.log("usertype1111111112222", that.chatList1, "sssssss");

      console.log(that.chatList1, "接受的消息");
    });
  },
  beforeDestroy() {
    // 在组件销毁时关闭WebSocket连接
    if (this.socket) {
      this.socket.close();
    }
  },
  // 处理从服务器接收的消息
  // onWebSocketMessage(event) {
  //   if (event.data) {
  //     const message11 = JSON.parse(event.data);
  //     console.log("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww:",message11)
  //     //    根据业务来处理数据
  //   }
  // },
};
</script>


<style scoped>
.xmessage1_kefu {
  /* z-index: 2; */
  background-color: lightgray;
  display: inline-block;
  height: auto;
  border: 1px solid lightgray;
  border-radius: 3px;
  padding: 10px;
  box-sizing: border-box;
  font-size: 13px;
  text-align: justify !important;
  line-height: 22px;
  width: auto;
  position: relative;
  margin-right: 20px;
  float: right;

  /* width: 200px;
  height: 100px; */
  /* font-size: 13px;
  text-align: justify !important;
  height: auto;
  border-radius: 5px;
  background-color: #ccc;
  position: relative;
  margin: 0 auto; */
}

.xmessage_box_kefu {
  z-index: 0;

  border-radius: 5px;

  position: relative;
}
.xmessage_box_kefu:before {
  z-index: 1;
  width: 0px;
  height: 0px;
  content: "";
  /* border-top: 15px solid transparent;
				border-bottom: 10px solid transparent;
				border-right: 12px solid rgb(229, 224, 224); */
  border-top: 2px solid transparent;
  border-bottom: 39px solid transparent;
  /* border-right: 24px solid lightgray; */
  border-left: 24px solid lightgray;
  position: absolute;
  top: 32px;
  left: 117px;
}

.shuang_kefu {
  /* padding: 2px; */
  padding-top: 8px;
  float: right;
}
.userimgliaot_kefu {
  float: right;
  display: flex;
  padding: 10px;
  width: 7%;
  height: 100%;
}
.kxmg > div {
  overflow: hidden;
}
.kxmg {
  margin-right: -70px;
  max-width: calc(100% - 50px);
  height: auto;
  width: 100%;
  overflow: hidden;
  /* float:right; */
  margin: 0 0 10px 0;
}
.shuang {
  /* padding: 2px; */
  padding-top: 8px;
  float: left;
}
.xfrom1 {
  padding: 1px;
  float: left;
  width: 100%;
  height: 16px;
  line-height: 16px;
  font-size: 12px;
  color: rgb(178, 178, 178);
  margin: 0 0 3px 0;
}
.xmessage1 {
  z-index: 2;
  background-color: lightgray;
  display: inline-block;
  height: auto;
  border: 1px solid lightgray;
  border-radius: 3px;
  padding: 10px;
  box-sizing: border-box;
  font-size: 13px;
  text-align: justify !important;
  line-height: 22px;
  width: auto;
  position: relative;
  margin-left: 10px;

  /* width: 200px;
  height: 100px; */
  /* font-size: 13px;
  text-align: justify !important;
  height: auto;
  border-radius: 5px;
  background-color: #ccc;
  position: relative;
  margin: 0 auto; */
}
.xmessage_box {
  z-index: 0;
  /* display: inline-block;
  height: auto;
  border: 1px solid lightgray;
  border-radius: 3px;
  padding: 10px;
  box-sizing: border-box;
  font-size: 13px;
  text-align: justify !important;
  line-height: 22px;
  width: auto; */
  border-radius: 5px;
  /* background-color: lightgray; */
  /* border: 1px solid lightgray; */
  position: relative;

  /* width: 200px;
  height: 100px; */
  /* font-size: 13px;
  text-align: justify !important;
  height: auto;
  border-radius: 5px;
  background-color: #ccc;
  position: relative;
  margin: 0 auto; */
}
.xmessage_box:before {
  z-index: 1;
  width: 0px;
  height: 0px;
  content: "";
  /* border-top: 15px solid transparent;
				border-bottom: 10px solid transparent;
				border-right: 12px solid rgb(229, 224, 224); */
  border-top: 2px solid transparent;
  border-bottom: 39px solid transparent;
  border-right: 24px solid lightgray;
  /* border-left: 5px solid transparent; */
  position: absolute;
  top: 32px;
  left: 0px;
}

.userimgliaot {
  float: left;
  display: flex;
  padding: 10px;
  width: 7%;
  height: 100%;
}
.userxsname {
  /* display: flex; */
  /* width: 50%; */
  float: left;
}
.userimg {
  float: left;
  display: flex;
  padding: 10px;
  width: 25%;
  height: 100%;
}
.super-box {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 78vh;
  background: rgb(252, 252, 252);
  box-shadow: rgb(0 0 0 / 16%) 0px 5px 40px;
  overflow: hidden;
}
.xchat-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgb(252, 252, 252);
  border-right: 1px solid #eee;
}
.xchat {
  flex: 3;
  display: flex;
  flex-direction: column;
  background: rgb(252, 252, 252);
}
.xtop {
  display: flex;
  align-items: center;
  width: 100%;
  height: 60px;
  background: #409eff;
  box-sizing: border-box;
  padding: 10px;
}
.xlogo {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.xsname {
  margin-left: 10px;
  font-size: 16px;
  color: white;
}
.xmid {
  float: left;
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  overflow-y: auto;
}
.xmsg {
  max-width: calc(100% - 50px);
  height: auto;
  width: 100%;
  overflow: hidden;
  margin: 0 0 10px 0;
}
.xmsg > div {
  overflow: hidden;
}
.xfrom {
  width: 100%;
  height: 16px;
  line-height: 16px;
  font-size: 12px;
  color: rgb(178, 178, 178);
  margin: 0 0 3px 0;
}

.xmessage {
  display: inline-block;
  height: auto;
  border: 1px solid lightgray;
  border-radius: 3px;
  padding: 10px;
  box-sizing: border-box;
  font-size: 13px;
  text-align: justify !important;
  line-height: 22px;
}

.xa > .xmessage {
  color: #333;
  background: white;
}
.xa {
  float: left;
  overflow-x: auto;
}
.xb {
  float: right;
  text-align: right;
}
.xb > p {
  text-align: right;
}
.xb > .xmessage {
  color: white;
  background: #409eff;
}
.xbottom {
  width: 100%;
  height: 100px;
  box-sizing: border-box;
  border-top: 1px solid #eee;
}
.xsendmsg {
  width: 100%;
  height: 58px;
  box-sizing: border-box;
  outline: none;
  resize: none;
  padding: 10px;
  border: none;
  background: rgb(252, 252, 252);
  font-size: 13px;
  font-family: auto;
  color: #333;
}
.xgsend {
  width: 100%;
  height: 40px;
  background-color: transparent;
  box-sizing: border-box;
  padding: 4px 10px;
}
.xsend {
  float: right;
  width: 60px;
  height: 32px;
  line-height: 32px;
  display: inline-block;
  vertical-align: middle;
  font-size: 13px;
  cursor: pointer;
  text-align: center;
  opacity: 1;
  color: white;
  border-width: 0px;
  outline: none;
  border-radius: 3px;
  text-decoration: none;
  background: #409eff;
}
.startchat {
  width: 62px;
  height: 62px;
  border: none;
  display: none;
  border-radius: 50%;
  background: #409eff;
  outline: none;
  cursor: pointer;
  box-shadow: rgba(0, 0, 0, 0.16) 0px 5px 14px;
}
.startchaticon {
  width: 24px;
  transform: translateY(2px);
}
.chat-user {
  background-color: white;
}
.chat-user > .xsname {
  color: #333;
}
.chat-user.selected {
  background-color: #c0c0c0;
}
.element-style-f {
  float: left;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: inline-block;
  background-color: #009bee;
  line-height: 37px;
  text-align: center;
  font-weight: bold;
  color: white;
}
.element-style-t {
  float: left;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: inline-block;
  background-color: #409eff;
  line-height: 37px;
  text-align: center;
  font-weight: bold;
  color: white;
}
.outline-user {
  color: gray;
  border-color: lightgray !important;
}
.rec-time {
  text-align: center;
  color: #727272;
  font-size: 12px;
}
.rec-chat-text-s {
  text-align: right;
}
.rec-chat-text-u {
  text-align: left;
}
.rec-chat-text-s > span {
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  outline: none;
  resize: none;
  padding: 3px 8px 0px;
  border: none;
  background-color: #409eff;
  font-size: 16px;
  font-family: auto;
  color: #333;
  border-radius: 3px;
}
.rec-chat-text-u > span {
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  outline: none;
  resize: none;
  padding: 3px 8px 0px;
  border: none;
  background-color: #409eff;
  font-size: 16px;
  font-family: auto;
  color: #333;
  border-radius: 3px;
}
</style>